/**
 * Created with JetBrains WebStorm.
 * User: kane
 * Date: 13-2-28
 * Time: 下午2:12
 * To change this template use File | Settings | File Templates.
 */
var client = require('../util/mongodb');

function User(user){
    this.name = user.name;
    this.password = user.password;
};

module.exports = User;
User.prototype.save = function (callback){
    var user = {
        name:this.name,
        password:this.password
    };
    client.open(function(err,db){
       if(err){
           return callback(err);
       }

        // 读取user集合
        db.collection('user',function(err,collection){
            if(err){
                client.close();
                return callback(err);
            }

            // 为name添加索引
            collection.ensureIndex('name',{unique:true});
            // 写入
            collection.insert(user,{safe:true},function(err,user){
                client.close();
                callback(err,user);
            });
        });
    });
}

User.get = function get(username, callback) {
    client.open(function(err, db) {
        if (err) {
            return callback(err);
        }
        // 讀取 users 集合
        db.collection('user', function(err, collection) {
            if (err) {
                client.close();
                return callback(err);
            }
            // 查找 name 屬性爲 username 的文檔
            collection.findOne({name: username}, function(err, doc) {
                client.close();
                if (doc) {
                    // 封裝文檔爲 User 對象
                    var user = new User(doc);
                    callback(err, user);
                } else {
                    callback(err, null);
                }
            });
        });
    });
};